package br.ufrj.dcc.ad.model;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.ufrj.dcc.ad.ADSimProperties;
import br.ufrj.dcc.ad.Simulator;
import br.ufrj.dcc.ad.event.BackgroundTrafficSendEvent;
import br.ufrj.dcc.ad.event.PackageReceivedByRouterEvent;

public class BackgroundTraffic {


	Logger logger = LoggerFactory.getLogger(BackgroundPackage.class);
	
	public BackgroundTraffic() {
	}
	
	public double sampleExponentialDistribution() {
		double sample = RandomGenerator.nextDouble();
		return -Math.log(sample) * ADSimProperties.getTfi();
	}
	
	public long sampleGeometricDistribution() {
		double sample = RandomGenerator.nextDouble();
		return (long) Math.ceil(Math.log(sample) / Math.log(( 1 - (1.0/ADSimProperties.getTft()) )));
	}

	public void sendPackages() {
		
		final Long numberOfPackages = sampleGeometricDistribution();

		for (int i = 0; i < numberOfPackages.intValue(); i++) {
			
			final BackgroundPackage pack = new BackgroundPackage();
			PackageReceivedByRouterEvent routerEvent = new PackageReceivedByRouterEvent(0d, pack);
			Simulator.addEvent(routerEvent);
			
		}
		
		final Double waitTime = (double) sampleExponentialDistribution();
		final BackgroundTrafficSendEvent nextbackgroundTrafficSendEvent = new BackgroundTrafficSendEvent(waitTime);
		Simulator.addEvent(nextbackgroundTrafficSendEvent);
		
		logger.info("Rajada de trafego de fundo - n pacotes: {}, proxima rajada em {} ms", numberOfPackages, waitTime/1000000d);
	}
	
}
